package com.sky.service.user.impl;

import com.sky.context.BaseContext;
import com.sky.mapper.user.AddressBookMapper;
import com.sky.pojo.AddressBook;
import com.sky.result.Result;
import com.sky.service.user.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void insert(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);
    }

    /**
     * 查询地址
     * @return
     */
    @Override
    public Result<List<AddressBook>> selectAll() {
        List<AddressBook> list =  addressBookMapper.selectAll(BaseContext.getCurrentId());
        return Result.success(list);
    }

    /**
     * 查询默认地址
     * @return
     */
    @Override
    public Result<AddressBook> selectDefaultAddresss() {

        AddressBook addressBook = addressBookMapper.selectDefaultAddresss(BaseContext.getCurrentId());
        return Result.success(addressBook);
    }

    /**
     * 设置默认地址
     * @param addressBook
     * @return
     */
    @Override
    public Result setDefault(AddressBook addressBook) {
        List<AddressBook> list =  addressBookMapper.selectAll(BaseContext.getCurrentId());
        for (AddressBook book : list) {
            if(book.getId() == addressBook.getId()){
                addressBookMapper.setDefault(addressBook.getId(),1);
            }else{
                addressBookMapper.setDefault(book.getId(),0);
            }
        }
        return Result.success();
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public Result<AddressBook> selectById(Long id) {
        AddressBook addressBook = addressBookMapper.selectById(id);
        return Result.success(addressBook);
    }

    /**
     * 修改地址
     * @param addressBook
     */
    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    /**
     * 删除地址
     * @param id
     * @return
     */
    @Override
    public Result deleteById(Long id) {
        addressBookMapper.deleteById(id);
        return Result.success();
    }
}
